package com.hd.trans.utils;

import android.view.MotionEvent;

import androidx.annotation.NonNull;

/**
 * 单击手势检测器
 */
public class SingleClickGestureDetector {
    private static final float MOVE_DISTANCE = 50;
    private static final long DEBOUNCE_INTERVAL_MILLISECONDS = 600L;

    //单击事件
    private final Runnable onSingleClickListener;
    //是否防止快速点击
    private final boolean isDebouncedClick;

    private float downX;
    private float downY;
    private boolean isMoved = false;

    private long lastClickTime = 0L;

    public SingleClickGestureDetector(Runnable onSingleClick){
        this(false,onSingleClick);
    }

    public SingleClickGestureDetector(boolean isDebouncedClick, Runnable onSingleClick) {
        this.onSingleClickListener = onSingleClick;
        this.isDebouncedClick = isDebouncedClick;
    }

    public boolean onTouchEvent(@NonNull MotionEvent event){
        boolean isClick = false;
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                isMoved = false;
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(event.getX() - downX) > MOVE_DISTANCE || Math.abs(event.getY() - downY) > MOVE_DISTANCE){
                    isMoved = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (!isMoved){
                    onSingleClick();
                    isClick = true;
                }
                break;
        }
        return isClick;
    }

    private void onSingleClick(){
        long now = System.currentTimeMillis();
        if (isDebouncedClick && now - lastClickTime < DEBOUNCE_INTERVAL_MILLISECONDS){
            return;
        }
        lastClickTime = now;

        if (onSingleClickListener == null)
            return;
        onSingleClickListener.run();
    }

    public void callOnClick(){
        onSingleClick();
    }

}
